package com.ruoyi.demo.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.demo.mapper.FriendAppMapper;
import com.ruoyi.system.mapper.FriendMapper;
import com.ruoyi.demo.service.IFriendAppService;
import com.ruoyi.system.domain.Friend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 好友申请 Service 实现
 * 
 * @author ruoyi
 */
@Service
public class FriendAppServiceImpl implements IFriendAppService {

    private static final Logger logger = LoggerFactory.getLogger(FriendAppServiceImpl.class);

    @Autowired
    private FriendAppMapper friendAppMapper;

    @Autowired
    private FriendMapper friendMapper;

    /**
     * 获取收到的好友申请列表
     */
    @Override
    public List<Friend> getReceivedList(Long userId) {
        if (userId == null) {
            throw new ServiceException("用户ID不能为空");
        }
        List<Friend> list = friendAppMapper.selectReceivedList(userId);
        return list;
    }

    @Override
    public List<Friend> selectAllFriends() {
        return friendAppMapper.selectAllFriends();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void acceptRequest(Long id) {
        if (id == null) {
            throw new ServiceException("申请ID不能为空");
        }
        
        logger.info("开始处理好友申请，ID: {}", id);
        
        // 1. 查询并验证申请记录
        Friend friend = friendMapper.selectFriendById(id);
        if (friend == null) {
            logger.error("好友申请不存在，ID: {}", id);
            throw new ServiceException("好友申请不存在");
        }
        
        logger.info("查询到好友申请记录: {}", friend);
        
        if (!"0".equals(friend.getStatus())) {
            logger.warn("好友申请已处理，ID: {}，当前状态: {}", id, friend.getStatus());
            throw new ServiceException("该申请已处理");
        }
        
        try {
            // 2. 更新原申请记录状态为已确认
            friend.setStatus("1");
            int rows = friendMapper.updateFriend(friend);
            if (rows <= 0) {
                logger.error("更新好友申请状态失败，ID: {}", id);
                throw new ServiceException("处理好友申请失败");
            }
            
            // 3. 插入反向好友记录
            Friend reverseFriend = new Friend();
            reverseFriend.setUserId(friend.getFriendId());
            reverseFriend.setFriendId(friend.getUserId());
            reverseFriend.setStatus("1");
            reverseFriend.setIsDeleted("0");
            
            rows = friendMapper.insertFriend(reverseFriend);
            if (rows <= 0) {
                logger.error("插入反向好友记录失败");
                throw new ServiceException("处理好友申请失败");
            }
            
            logger.info("成功处理好友申请，ID: {}", id);
        } catch (Exception e) {
            logger.error("处理好友申请时发生异常", e);
            throw new ServiceException("处理好友申请失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectRequest(Long id) {
        if (id == null) {
            throw new ServiceException("申请ID不能为空");
        }
        
        // 添加日志
        logger.info("开始处理好友申请拒绝，ID: {}", id);
        
        Friend friend = friendAppMapper.selectFriendById(id);
        if (friend == null) {
            logger.error("好友申请不存在，ID: {}", id);
            throw new ServiceException("好友申请不存在");
        }
        
        logger.info("查询到好友申请记录: {}", friend);
        
        if (!"0".equals(friend.getStatus())) {
            logger.warn("好友申请已处理，ID: {}，当前状态: {}", id, friend.getStatus());
            throw new ServiceException("该申请已处理");
        }
        
        // 拒绝好友申请，状态改为2
        friend.setStatus("2");
        try {
            int rows = friendAppMapper.updateFriend(friend);
            if (rows <= 0) {
                logger.error("更新好友申请状态失败，ID: {}", id);
                throw new ServiceException("处理好友申请失败");
            }
            logger.info("成功拒绝好友申请，ID: {}", id);
        } catch (Exception e) {
            logger.error("处理好友申请拒绝时发生异常", e);
            throw new ServiceException("处理好友申请失败：" + e.getMessage());
        }
    }
}
